<style lang="scss" scoped="">

  @import "../../assets/chartEdit";
  @import "../../assets/mixins";

  .page-main-left h4 {
    cursor: pointer;
    padding: 0;
    margin: 0;
  }

  .current-dataset-part {
    background: #fff;
    border: 1px solid #eee;
    border-radius: 5px;

    height: 80px;
    > div {
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;

      &:first-child, &.current-dataset-list {
        padding: 25px 10px;
        z-index: 2;
        display: flex;
        justify-content: center;
        .current-dataset-join {
          padding: 0 10px;
        }
      }
      &:last-child {
        text-align: center;
        line-height: 80px;
        color: $warning-color;
      }
      &.save-tools {
        right: 10px;
        width: auto;
        height: 20px;
        top: 10px;
        left: auto;
        z-index: 20;
      }
    }
  }

  .current-dataset-part {
    .dataset-current-ghost {
      border: 2px solid $warning-color;
      text-indent: -20000px;
    }
  }

  .join-form {
    .el-row {
      margin-top: 10px;
    }
    .el-select {
      width: 100%;
    }
  }
</style>
<template>
  <div>

    <div class="page-main-body">
      <div class="page-main-left" :style="'width:'+leftWidth+'px'">
        <el-menu :default-active="pathUrl+'/ds'" mode="horizontal" :router="true">
          <el-menu-item :index="pathUrl">图表项</el-menu-item>
          <el-menu-item :index="pathUrl+'/ds'">数据源
          </el-menu-item>
        </el-menu>
        <div class="line"></div>

        <div class="left-menu">
          <h3>
            <i class="el-icon-plus pull-right" @click="addDataSource"></i>连接</h3>
          <template v-for="dataSource in dataSourceList">
            <h4 @click="editDataSource(dataSource)" class="clearfix">
              <i class="el-icon-edit pull-right"></i> <f-a name="data"></f-a> {{dataSource.name}}
            </h4>
            <div>
              <draggable v-model="dataSource.datasetList" :options="dragOp.f">
                <transition-group class="menu-series">
                  <div v-for="dataSet in dataSource.datasetList" :key="dataSet.datasetId">
                    <span>{{dataSet.title}}</span>
                    <el-dropdown @command="datasetCommand">
                      <span class="el-dropdown-link">
                       <i class="el-icon-arrow-down el-icon--right"></i>
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item :command="{operate:'rename',dataSet:dataSet}">修改名称
                        </el-dropdown-item>
                        <el-dropdown-item :command="{operate:'remove',dataSet:dataSet}">移除</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </div>
                </transition-group>
              </draggable>
            </div>
          </template>
        </div>
      </div>
      <div class="page-main-right" :style="'width:'+rightWidth">
        <div class="chart-tag-axis">
          <h3>
            <el-input v-model="currentDataSetTitle" readonly=""></el-input>
          </h3>

          <div>
            <draggable v-model="currentDataSetList" :options="dragOp.t" class="current-dataset-part">
              <transition-group tag="div" class="current-dataset-list">
                <div v-for="(dataSet,index) in currentDataSetList" :key="index">
                  <span v-if="index>0" class="current-dataset-join">

                    <el-button size="small" @click="joinVisible=true" round>连接</el-button>
                  </span>

                  <el-dropdown size="small" split-button type="primary" @command="commandCurrentDataSetList">
                    {{dataSet.title}}
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item :command="{operate:'remove',index:index}">移除</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </transition-group>
              <div class="save-tools">
                <el-button size="small" @click.stop="bindDataset">保存</el-button>
              </div>
              <div v-show="currentDataSetList.length==0">把左侧表拖到此处</div>

            </draggable>
          </div>

        </div>
        <transition name="scale" mode="out-in" appear>
          <router-view></router-view>
        </transition>

      </div>
    </div>

    <el-dialog
      title="表连接方式"
      :visible.sync="joinVisible"
      :before-close="saveJoinInfo" width="600px" append-to-body>
      <div>
        <el-radio-group v-model="joindataset.joinType">
          <el-radio-button label="inner">内联</el-radio-button>
          <el-radio-button label="left">左连</el-radio-button>
          <el-radio-button label="right">右连</el-radio-button>
          <el-radio-button label="full">外连</el-radio-button>
        </el-radio-group>
        <div class="join-form no-radius" v-if="currentDataSetList.length>1">
          <div style="margin:20px 0">
            别名:
            <el-input type="text" size="small" v-model="joindataset.title" placeholder="请输入"></el-input>
          </div>

          <el-row type="flex">
            <el-col :span="10">
              {{currentDataSetList[0].title}}
            </el-col>
            <el-col :span="4" style="text-align:center">
              关系
            </el-col>
            <el-col :span="10" style="text-align:right">
              {{currentDataSetList[1].title}}
            </el-col>
          </el-row>

          <el-row type="flex">
            <el-col :span="10">
              <el-select size="small" v-model="joindataset.rules[0].leftField" placeholder="请选择">
                <el-option :label="field.title" :value="field.id" :key="field.id" v-for="field in leftFieldList">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select size="small" v-model="joindataset.rules[0].relation" placeholder="请选择">
                <el-option value="=" label="=">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="10">
              <el-select size="small" v-model="joindataset.rules[0].rightField" placeholder="请选择">
                <el-option :label="field.title" :value="field.id" :key="field.id" v-for="field in rightFieldList">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="joinVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveJoin">确 定</el-button>
      </div>
    </el-dialog>
    <page-right :show="showDsForm" @right-close="resetRightBox">
      <ds-form @change="itemChange" @close="resetRightBox" :form="currentDataSource"></ds-form>
    </page-right>
  </div>
</template>

<script>
  import {http, chart, datasource, joindataset, dataset, field} from '../../resources';
  import dsForm from '../dataSource/form/form.vue';
  import utils from '@/tools/utils';
  import opera from '@/action/opera';

  export default {
    components: {
      dsForm
    },

    data: function () {
      return {
        chartInfo: {}, // 当前表信息
        leftWidth: 240, // 左侧宽度
        showDsForm: false, // 右侧显示数据源表单
        dataSourceList: [],
        currentDataSetList: [],
        currentDataSource: {},
        joinVisible: false,
        joindataset: {
          title: '',
          leftId: '',
          rightId: '',
          joinType: 'inner',
          rules: [
            {
              leftField: '',
              rightField: '',
              relation: '='
            }
          ]
        },
        leftFieldList: [],
        rightFieldList: [],
        dragOp: {
          f: {
            group: {
              name: 'ds',
              pull: 'clone',
              put: false
            },
            sort: false,
            ghostClass: 'dataset-current-ghost'
          },
          t: {
            group: {
              name: 'ds'
            },
            disabled: false
          }
        },
        currentDataSetId: '',
        currentDataSetTitle: ''
      };
    },
    computed: {
      rightWidth: function () {
        let width = this.$store.state.bodyWidth - this.leftWidth;
        width = width - 40;
        return width + 'px';
      },
      pathUrl: function () {
        return `/project/${this.$route.params.projectId}/chart/${this.$route.params.chartId}`;
      }
    },
    watch: {
      chartId: {
        handler(form) {
          this.getChartInfo();
        },
        deep: true
      },
      currentDataSetList: {
        handler(ds) {
          this.joinVisible = this.dragOp.t.disabled = ds.length >= 2;
          if (ds.length < 2) {
            this.currentDataSetId = ds[0] ? ds[0].datasetId : '';
            this.currentDataSetTitle = ds[0] ? ds[0].title : '';
          } else {
            this.joindataset.leftId = ds[0].datasetId;
            this.joindataset.rightId = ds[1].datasetId;
            this.getcurrentDataSetListField();
          }
        },
        deep: true
      },
      currentDataSetId: function (currentDataSetId) {
        if (currentDataSetId) {
          this.$store.commit('changeCurrentDatasetId', currentDataSetId);
        }
      }

    },
    mounted() {
      this.getChartInfo();

    },
    methods: {
      getcurrentDataSetListField() {

        this.currentDataSetList.forEach((item, index) => {
          field.query({datasetId: item.datasetId}).then(res => {
            if (index === 0) {
              this.leftFieldList = res.data.data;
            } else {
              this.rightFieldList = res.data.data;
            }
          });
        });
      },
      getChartInfo: function () {
        chart.get(this.$route.params.chartId).then(res => {
          this.chartInfo = res.data;
          this.currentDataSetId = this.chartInfo.datasetId;
          this.getDataSoureList();
        });
      },
      getDataSoureList() {
        let currentDatasetId = this.currentDataSetId;
        datasource.query({projectId: this.$route.params.projectId}).then(res => {
          res.data.data.forEach(item => {
            item.datasetList = [];
            dataset.query({datasourceId: item.datasourceId}).then(res => {
              item.datasetList = res.data.data;
              item.datasetList.forEach(ds => {
                if (ds.datasetId === currentDatasetId) {
                  this.currentDataSetList = [ds];
                }
              });
            });
          });
          this.dataSourceList = res.data.data;
        });
      },
      addDataSource() {
        this.showDsForm = true;
      },
      editDataSource(ds) {
        this.currentDataSource = ds;
        this.showDsForm = true;
      },

      resetRightBox() {
        this.currentDataSource = {};
        this.showDsForm = false;
      },
      itemChange(datasoureId) {
        let isNew = true;
        for (let item of this.dataSourceList) {
          if (item.datasourceId === datasoureId) {
            isNew = false;
            dataset.query({datasourceId: item.datasourceId}).then(res => {
              item.datasetList = res.data.data;
            });
            break;
          }
        }
        if (isNew) {
          datasource.get(datasoureId).then(res => {
            let item = res.data;
            item.datasetList = [];
            dataset.query({datasourceId: datasoureId}).then(res => {
              item.datasetList = res.data.data;
            });
            this.dataSourceList.push(item);
          });

        }
      },
      commandCurrentDataSetList(command) {
        if (command.operate === 'remove') {
          this.currentDataSetList.splice(command.index, 1);
        }
      },
      saveJoinInfo(done) {
        done();
      },
      bindDataset() {
        if (this.currentDataSetId) {
          chart.update(this.$route.params.chartId, {datasetId: this.currentDataSetId.toString()}).then(res => {

          });
        }
      },
      saveJoin() {
        joindataset.save(this.joindataset).then(res => {
          this.joinVisible = false;
          this.currentDataSetId = res.data.datasetId;
        });
      },
      datasetCommand(commandObj) {
        let currentDataSet = commandObj.dataSet;
        switch (commandObj.operate) {
          case 'rename':
            opera.rename(dataset, currentDataSet.datasetId, currentDataSet.title).then(res => {
              this.getDataSoureList();
            });
            break;
          case 'remove':
            opera.delete(dataset, currentDataSet.datasetId).then(res => {
              this.getDataSoureList();
            });
            break;
          default:
            break;
        }

      }

    }
  };
</script>
